<template>

    <div class="search">
        <el-select v-model="searchKey" filterable remote placeholder="Please enter a keyword"
            :remote-method="remoteMethod" :loading="optionloading" clearable @change="serchList">
            <el-option v-for="item in searchOptions" :key="item.name" :label="item.name" :value="item.name" />
        </el-select>
        <el-button type="primary" style="margin-left: 3%;" @click="addUser">
            <el-icon>
                <Plus />
            </el-icon>
            <span>添加</span>
        </el-button>
    </div>

    <br />
    <el-button @click="exportExcel" style="margin-bottom: 20px;margin-left: 1%;">导出表格</el-button>
    <br />
    <el-table :data="tableData" height="450" style="width: 100%" v-loading="tableLoading">
        <el-table-column label="头像" width="180">
            <template #default="scope">
                <div style="display: flex; align-items: center">
                    <el-avatar :src="scope.row.headimgurl"> user </el-avatar>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="degree" label="学历" width="180" />
        <el-table-column prop="class" label="班级" width="180" />
        <el-table-column prop="productUrl" label="项目" width="180" />
        <el-table-column prop="cTime" label="创建时间" width="180" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="success" :icon="View" circle v-permission:read="permission" />
                <el-button type="primary" :icon="Edit" circle :disabled="disabled" v-permission:edit="permission"
                    @click="EditStu(scope.row)" />
                <el-button type="danger" :icon="Delete" circle :disabled="disabled" v-permission:delete="permission"
                    @click="delList(scope.row.sId)" />
            </template>
        </el-table-column>
    </el-table>
    <br />
    <div class="paginat">
        <el-pagination background @current-change="getnewStuList" :total="totalPage" :page-size="pageSize"
            :current-page="currentpage" />
    </div>
    <dialogCom :Visible="Visible" :title="title" :datalist="datalist" @dataVaildatasu="dataVaildatasu"
        @dialogCancel="dialogCancel" @close="close">
        <template v-slot:upload>
            <el-upload method="post" name="headimgurl" action="/api/students/uploadStuAvatar"
                :on-success="handleAvatarSuccess" list-type="picture-card" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" width="100" class="avatar" />
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
        </template>
    </dialogCom>
</template>
<script setup>
import { ref, onMounted, reactive } from "vue"
import {
    Delete,
    View,
    Edit,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus"
//引入接口
import *as api from "../../../../api/studentlist.js"
import dialogCom from "../../../../components/dialog/index.vue"
import qee from "qf-export-excel"

let tableData = ref([])

let searchKey = ref("")

let optionloading = ref(false)

let tableLoading = ref(false)

let searchOptions = ref([])

let disabled = ref(false)

//设置total的总数居，
let totalPage = ref()

let currentpage = ref()


let pageSize = ref(10)

let permission = ref()

let title = ref()
//取sessionStorage里的permission的权限
permission.value = JSON.parse(sessionStorage.getItem("permission"))


let Visible = ref(false)

let imageUrl = ref()


//导出表格
let exportExcel = () => {

    //定义表头 
    let titleSource = [
        {
            title: "姓名",
            key: 'name'
        },
        {
            title: "年龄",
            key: 'age'
        },
        {
            title: "头像地址",
            key: 'headimgurl'
        },
        {
            title: '学历',
            key: 'degree'
        },
        {
            title: "班级",
            key: 'class'
        }
    ]

    qee(titleSource, tableData.value, '工资单')
}



let datalist = reactive(
    {
        class: {
            label: "班级",
            value: ""
        },
        name: {
            label: "名字",
            value: ""
        },
        age: {
            label: "年龄",
            value: ""
        },
        city: {
            label: "城市",
            value: ""
        },
        degree: {
            label: "学历",
            value: ""
        },
        productUrl: {
            label: "项目地址",
            value: ""
        },
        description: {
            label: "评价",
            value: ""
        },
    }
)


//dialog关闭的逻辑
let close = () => {
    Visible.value = false
    let keys = Object.keys(datalist)
    keys.forEach(p => {
        datalist[p].value = ""
    })
    imageUrl.value = ""
}



//用户上传图片前的逻辑
let beforeAvatarUpload = (rawFile) => {

    let arr = ["image/jpeg", "image/jpg", "image/png", "image/gif"]
    if (!arr.includes(rawFile.type)) {
        ElMessage({
            type: 'error',
            message: `你当前上传的格式为${rawFile.type},必须用"image/jpeg","image/jpg","image/png","image/gif"`,
        })
    }
    console.log(rawFile, "rawFile");

}


//用户上传图片成功

let handleAvatarSuccess = (response, uploadFile) => {
    console.log("response======", response);
    console.log("uploadFile======", uploadFile);
    if (response.state) {
        ElMessage({
            type: 'success',
            message: '上传成功',
        })
    }
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
}


//增加用户列表
let addUser = () => {
    title.value = "增加用户"
    // console.log(11);
    Visible.value = true
    // console.log(datalist);
}


//数据校验成功后的逻辑
let dataVaildatasu = async (form) => {
    // flag.value = !flag.value
    // console.log(form,"jhgjhgjhg");
    //
    if (title.value == "增加用户") {
        let obj = {
            class: datalist.class.value,
            name: datalist.name.value,
            age: datalist.age.value,
            city: datalist.city.value,
            degree: datalist.degree.value,
            productUrl: datalist.productUrl.value,
            description: datalist.description.value,
            headimgurl: imageUrl.value
        }
        try {
            console.log(111);
            let res = api.addStudentsList(obj)
            getStuList()
            Visible.value = false
            form.resetFields()
            ElMessage({
                type: 'success',
                message: '增加成功',
            })
        } catch (error) {
            console.log(error);
            Visible.value = false
            form.resetFields()
        }

        console.log(obj, "kkkkkk");
        //   for (const key in datalist) {
        //     console.log(key);
        //   }
        Visible.value = false
        console.log("datalist====", datalist);
    } else {
        // console.log(datas.value);
        let obj = {
            sId: datas.value.sId,
            class: datalist.class.value,
            name: datalist.name.value,
            age: datalist.age.value,
            city: datalist.city.value,
            degree: datalist.degree.value,
            productUrl: datalist.productUrl.value,
            description: datalist.description.value,
            headimgurl: imageUrl.value
        }
        // console.log(obj, "kkkk");
        try {
            let res = await api.editStudentsList(obj)
            Visible.value = false
            ElMessage({
                type: 'success',
                message: '修改成功',
            })
            getStuList()
            form.resetFields()
        } catch (error) {
            console.log(error);
            Visible.value = false
        }

    }
}

//控制行的数据
let datas = ref()


//数据回显的逻辑
let EditStu = (data) => {
    datas.value = data
    title.value = "修改用户"
    Visible.value = true
    console.log(data, "kkk");
    let keys = Object.keys(datalist)
    keys.forEach((p) => {
        datalist[p].value = data[p]
    })
    imageUrl.value = data.headimgurl

}



//点击dialog的取消的逻辑
let dialogCancel = () => {
    Visible.value = false


}


//搜索框的逻辑
let serchList = async (key) => {

    searchKey.value = key
    try {
        let res = await api.searchStudentsList(key)
        totalPage.value = res.data.total
        tableData.value = res.data.data
        let arr = res.data.data.map((p) => { return { name: p.name } })
        let kong1 = []
        arr.forEach(p => {
            kong1.push(p.name)
        })
        let newSet = new Set(kong1)
        let newArr = [...newSet]
        let kong = []
        newArr.forEach((p) => {
            let obj = {
                name: p
            }
            kong.unshift(obj)
        })
        searchOptions.value = kong
        // console.log(searchOptions.value, "kkkk");
        optionloading.value = false

    } catch (error) {
        console.log(error);
    }
}

//远程联想的逻辑
let remoteMethod = async (key) => {
    if (key) {
        console.log(111111111);

        return
    }

    try {
        optionloading.value = true
        let res = await api.searchStudentsList(key)


        let arr = res.data.data.map((p) => { return { name: p.name } })
        let kong1 = []
        arr.forEach(p => {
            kong1.push(p.name)
        })
        let newSet = new Set(kong1)
        let newArr = [...newSet]
        let kong = []
        newArr.forEach((p) => {
            let obj = {
                name: p
            }
            kong.unshift(obj)
        })
        searchOptions.value = kong

        optionloading.value = false
    } catch (error) {
        console.log(error);
    }

}


//删除逻辑
let delList = async (id) => {

    ElMessageBox.confirm(
        '你要永久删除吗?',
        'Warning',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
        .then(
            async () => {
                let res = await api.delStudentsList(id)
                getStuList(currentpage.value)
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }

        )
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}


//按钮级鉴权
let vPermission = {
    mounted(el, bniding) {
        // console.log(el, bniding);
        if (bniding.value.includes(bniding.arg)) {
        } else {
            // console.log(permission, "uuuuu");
            disabled.value = true
        }

    }
}

//取分页的数据
let getnewStuList = async (newPage) => {

    currentpage.value = newPage
    // console.log(11113);
    if (searchKey.value) {
        console.log(12121);
        let res = await api.searchStudentsList(searchKey.value, newPage)
        totalPage.value = res.data.total
        tableData.value = res.data.data


    } else {
        try {

            getStuList(newPage)
            currentpage.value = newPage

        } catch (error) {

        }
        console.log(newPage, "llll");
        getStuList(newPage)


    }


}

//封装获取数据的方法
let getStuList = async (newPage) => {
    try {
        tableLoading.value = true
        let res = await api.getStudentsList(newPage)
        tableLoading.value = false
        tableData.value = res.data.data
        console.log(res, "llll");
        totalPage.value = res.data.total
    } catch (error) {

    }
}

onMounted(async () => {
    getStuList()
    // delList()
})

</script>


<script>
export default {
    meta: {
        title: 'xyxmgl', name: '学员项目管理', icon: 'icon-xiangmuguanli'
    }
}
</script>
